﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure;
using ServiceStack;
using DormMS.IService;
using DormMS.Model;
using DormMS.Model.SearchModels;
using DormMS.Model.ViewModels;
using Infrastructure.Dao;
using SqlSugar;

namespace DormMS.Service
{
    public class SpecService : ISpecService
    {
        public List<Product_SpecType> SpecTypeManage(BaseSearchModel search, out int total)
        {
            StringBuilder wherestr = new StringBuilder();
            wherestr.Append(" 1=1 ");
            //int totalcount = 0;
            return BaseService.LoadPageEntities<Product_SpecType>(search.Skip, search.Take, out total, wherestr.ToString(), search.OrderByFields);
        }


        public Result SpecTypeEdit(Product_SpecType specType, int currentUserId)
        {
            if (specType == null)
            {
                return Result.Failure("传入参数有误");
            }

            var isexist = BaseService.LoadEntitiesCount<Product_SpecType>(m => m.SpecTypeName == specType.SpecTypeName && m.Id != specType.Id);
            if (isexist > 0)
            {
                return Result.Failure("该类型已存在");
            }

            if (specType.Id == 0)
            {
                specType.AddUserId = currentUserId;
                BaseService.AddEntity(specType);
            }
            else
            {
                specType.EditUserId = currentUserId;
                specType.EditTime = DateTime.Now;
                BaseService.UpdateEntity(specType);
            }
            return Result.Success();
        }


        public Result DelSpecType(int Id, int currentUserId)
        {
            bool isd = true;
            if (Id == 0)
            {
                return Result.Failure("传入Id不能为0");
            }

            var spectype = BaseService.LoadEntity<Product_SpecType>(m => m.Id == Id);
            var spectemp = BaseService.LoadEntities<Product_SpecTemplate>(m => m.SpecTypeId == Id);
            foreach (var item in spectemp)
            {
                var spectempitems = BaseService.LoadEntities<Product_SpecTemplateItem>(m => m.SpecTemplateId == item.Id);
                if (spectempitems != null && spectempitems.Count > 0)
                {
                    spectempitems.ForEach(m =>
                    {
                        var smodel = BaseService.LoadEntities<Product_Spec>(s => s.IsDeleted == false && s.SpecIds.Contains(m.Id.ToString()) && s.SpecNames.Contains(m.SpecItemName));
                        if (smodel != null&&smodel.Count>0)
                        {
                            isd = false;
                        }
                    });
                }

            }

            if (!isd)
            {
                return Result.Failure("该规格类型下已有规格项在使用，无法删除");
            }

            spectype.IsDeleted = true;
            spectype.EditTime = DateTime.Now;
            spectype.EditUserId = currentUserId;
            BaseService.UpdateEntity(spectype);

            //var spectemp = BaseService.LoadEntities<Product_SpecTemplate>(m => m.SpecTypeId == Id);
            if (spectemp != null && spectemp.Count > 0)
            {
                foreach (var item in spectemp)
                {
                    item.IsDeleted = true;
                    item.EditTime = DateTime.Now;
                    item.EditUserId = currentUserId;
                    BaseService.UpdateEntity(item);

                    var spectempitems = BaseService.LoadEntities<Product_SpecTemplateItem>(m => m.SpecTemplateId == item.Id);
                    if (spectempitems != null && spectempitems.Count > 0)
                    {
                        spectempitems.ForEach(m =>
                        {
                            m.IsDeleted = true;
                            m.EditTime = DateTime.Now;
                            m.EditUserId = currentUserId;
                            BaseService.UpdateEntity(m);
                        });
                    }

                }
            }
            return Result.Success();
        }


        public List<SpecTemplateViewModel> SpecTemplateManage(SpecTemplateSearchModel search, out int total)
        {
            var response = new List<SpecTemplateViewModel>();
            StringBuilder wherestr = new StringBuilder();
            wherestr.Append(" 1=1 ");
            if (search.SpecType > 0)
            {
                wherestr.AppendFormat(" and SpecTypeId={0} ", search.SpecType);
            }
            var templist = BaseService.LoadPageEntities<Product_SpecTemplate>(search.Skip, search.Take, out total, wherestr.ToString(), search.OrderByFields);
            if (templist != null && templist.Count > 0)
            {
                templist.ForEach(m =>
                {
                    var model = m.ConvertTo<SpecTemplateViewModel>();
                    var spectype = BaseService.LoadEntity<Product_SpecType>(t => t.Id == m.SpecTypeId);
                    if (spectype != null)
                    {
                        model.SpecTypeName = spectype.SpecTypeName;
                    }

                    var tempitemlist = BaseService.LoadEntities<Product_SpecTemplateItem>(s => s.SpecTemplateId == m.Id);
                    if (tempitemlist != null && tempitemlist.Count > 0)
                    {
                        tempitemlist.ForEach(n => model.SpecTemplateItems += n.SpecItemName + ",");
                        model.SpecTemplateItems.TrimEnd(',');
                    }
                    response.Add(model);
                });
            }
            return response;
        }

        public List<Product_SpecType> GetSpecTypeList()
        {
            return BaseService.LoadEntities<Product_SpecType>(m => m.Id > 0);
        }


        public Result SpecTemplateEdit(Product_SpecTemplate specTemplate, int currentUserId)
        {
            if (specTemplate == null)
            {
                return Result.Failure("传入参数有误");
            }

            if (specTemplate.Id == 0)
            {
                specTemplate.AddUserId = currentUserId;
                BaseService.AddEntity(specTemplate);
            }
            else
            {
                specTemplate.EditUserId = currentUserId;
                specTemplate.EditTime = DateTime.Now;
                BaseService.UpdateEntity(specTemplate);
            }
            return Result.Success();
        }


        public Result DelSpecTemplate(int Id, int currentUserId)
        {
            bool isd = true;
            var spectemp = BaseService.LoadEntity<Product_SpecTemplate>(m => m.Id == Id);
            if (spectemp == null || spectemp.Id == 0)
            {
                return Result.Failure("该数据不存在");
            }


            var spectempitems = BaseService.LoadEntities<Product_SpecTemplateItem>(m => m.SpecTemplateId == spectemp.Id);
            if (spectempitems != null && spectempitems.Count > 0)
            {
                spectempitems.ForEach(m =>
                {
                    var smodel = BaseService.LoadEntities<Product_Spec>(s => s.IsDeleted == false && s.SpecIds.Contains(m.Id.ToString()) && s.SpecNames.Contains(m.SpecItemName));
                    if (smodel != null&&smodel.Count>0)
                    {
                        isd = false;
                    }
                });
            }
            if (!isd)
            {
                return Result.Failure("该规格模板已使用，无法删除");
            }

            spectemp.IsDeleted = true;
            spectemp.EditTime = DateTime.Now;
            spectemp.EditUserId = currentUserId;
            BaseService.UpdateEntity(spectemp);

            if (spectempitems != null && spectempitems.Count > 0)
            {
                spectempitems.ForEach(m =>
                {
                    m.IsDeleted = true;
                    m.EditTime = DateTime.Now;
                    m.EditUserId = currentUserId;
                    BaseService.UpdateEntity(m);
                });
            }

            return Result.Success();
        }


        public Result SaveSpecTemplateItem(int TemplateId, string TempItems, int currentUserId)
        {
            Result r = new Result();
            var itemlist = new List<string>();
            if (!TempItems.IsNullOrEmpty())
            {
                itemlist = TempItems.TrimEnd(',').Split(',').ToList();
            }

            var orginItems = BaseService.LoadEntities<Product_SpecTemplateItem>(m => m.SpecTemplateId == TemplateId);
            if (orginItems != null && orginItems.Count > 0)
            {
                orginItems.ForEach(m =>
                {
                    if (!itemlist.Contains(m.SpecItemName))
                    {
                        var smodel = BaseService.LoadEntities<Product_Spec>(s => s.IsDeleted == false && s.SpecIds.Contains(m.Id.ToString()) && s.SpecNames.Contains(m.SpecItemName));
                        if (smodel != null && smodel.Count > 0)
                        {
                            r.isSuccess = false;
                            r.msg = "该规格项已使用，无法删除";
                        }
                        else
                        {
                            m.IsDeleted = true;
                            m.EditTime = DateTime.Now;
                            m.EditUserId = currentUserId;
                            BaseService.UpdateEntity(m);
                            r.isSuccess = true;
                            r.msg = "操作成功";
                        }
                    }
                });
                itemlist.ForEach(n =>
                {
                    if (!orginItems.Any(a => a.SpecItemName == n))
                    {
                        BaseService.AddEntity(new Product_SpecTemplateItem
                        {
                            AddUserId = currentUserId,
                            SpecItemName = n,
                            SpecTemplateId = TemplateId
                        });
                        r.isSuccess = true;
                        r.msg = "操作成功";
                    }
                });
            }
            else
            {
                itemlist.ForEach(n =>
                {
                    BaseService.AddEntity(new Product_SpecTemplateItem
                    {
                        AddUserId = currentUserId,
                        SpecItemName = n,
                        SpecTemplateId = TemplateId
                    });
                    r.isSuccess = true;
                    r.msg = "操作成功";
                });
            }
            return r;
        }

        public void AddSpecItem(Product_SpecTemplateItem entity)
        {
            using (var db = DbConfig.GetInstance())
            {
                var model = db.Queryable<Product_SpecTemplateItem>().SingleOrDefault(t => t.SpecItemName == entity.SpecItemName && t.SpecTemplateId == entity.SpecTemplateId);
                if (model != null)
                {
                    throw new Exception("该规格项名称已存在");
                }

                db.Insert(entity);
            }
        }


    }
}
